package com.chendechao.lib_base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest

abstract class BaseFragment<VB : ViewBinding, MV : ViewModel>(
    private val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : Fragment() {

    protected lateinit var binding: VB
    protected abstract val viewModel: MV

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = bindingInflater.invoke(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    abstract fun initView()
    abstract fun initData()

    protected open fun <S> collectState(stateFlow: StateFlow<S>, collector: (S) -> Unit) {
        lifecycleScope.launchWhenStarted {
            stateFlow.collectLatest(collector)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
//        val bindingClass = binding::class.java
//        if (bindingClass.name.endsWith("Binding")) {
//            val unbindMethod = bindingClass.getMethod("unbind")
//            unbindMethod.invoke(binding)
//        }
    }
}